<?php

namespace App\Controller\WebSocket;

use App\Model\PcUserFd;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Engine\WebSocket\Frame;
use Hyperf\Engine\WebSocket\Response;
use Hyperf\WebSocketServer\Constant\Opcode;

class ConsumerMsgPushController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage($server, $frame): void
    {
       
        
        $response = (new Response($server))->init($frame);
        if ($frame->opcode == Opcode::PING) {
            // 如果使用协程 Server，在判断是 PING 帧后，需要手动处理，返回 PONG 帧。
            // 异步风格 Server，可以直接通过 Swoole 配置处理，详情请见 https://wiki.swoole.com/#/websocket_server?id=open_websocket_ping_frame
            
            $response->push(new Frame(opcode: Opcode::PONG));
            return;
        }
        
        $response->push(new Frame(payloadData: json_encode(['onMessage' => $frame->data],
        JSON_UNESCAPED_UNICODE)));
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        //网站退出后把数据库fd删除
        PcUserFd::where('fd', $fd)->delete();
        //var_dump("关闭fd{$fd}");
    }

    public function onOpen($server, $request): void
    {

        $response = (new Response($server))->init($request);
        //获取装置唯一值进行上下线更新
        if (isset($request->get['session_id'])) {
            $session_id = PcUserFd::where('session_id', $request->get['session_id'])->value('id');
            if (!empty($session_id)) {
                PcUserFd::where('session_id', $request->get['session_id'])->update(['fd' => $request->fd]);
            } else {
                PcUserFd::insert([
                    'session_id' => $request->get['session_id'],
                    'fd' => $request->fd,
                    'work_area_stand_id' => $request->get['work_area_stand_id']
                ]);
            }
        }
        $response->push(new Frame(payloadData: json_encode([
            'onOpen' => '连接成功',
            'get' => $request->get,
            'fd' => $request->fd
        ], JSON_UNESCAPED_UNICODE)));
    }
}